package com.nl.controller.web.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.MD5;
import com.nl.controller.web.bean.SmsCounty;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.bean.SmsRule;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.mapper.SmsUserMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsUserService {
    @Autowired
    private SmsUserMapper smsUserMapper;

    @Autowired
    private CommonService commonService;

    @SystemServiceLog(description = "按照条件查询用户的信息", value = false)
    public PageInfo<SmsUsers> findUser(int page, int limit, String msisdn, String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("msisdn", msisdn);
        map.put("userName", name);
        PageHelper.startPage(page, limit);
        List<SmsUsers> list;
        try {
            list = smsUserMapper.findUser(map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("按照条件查询用户的信息");
            throw new SmsException("按照条件查询用户的信息");
        }
        //查询用户的角色信息
        if (list.size() > 0) {
            for (SmsUsers user : list) {
                List<SmsRule> roleList = new ArrayList<>();
                try {
                    roleList = smsUserMapper.findRuleNameByUserid(user.getUserId());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("获取用户角色");
                    throw new SmsException("获取用户角色");
                }
                StringBuffer sbf = new StringBuffer();
                int i = 1;
                if (roleList.size() > 0) {
                    for (SmsRule smsRule : roleList) {
                        sbf.append(smsRule.getRoleName());
                        if (i < roleList.size()) {
                            sbf.append(",");
                            i++;
                        }
                    }
                    user.setSmsRuleName(sbf.toString());
                }
            }
        }
        PageInfo<SmsUsers> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @SystemServiceLog(description = "查询所有角色的信息", value = false)
    public List<SmsRule> findRule(String duty) {
        List<SmsRule> list = new ArrayList<>();
        try {
            list = smsUserMapper.findRule(duty);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询所有角色的信息");
            throw new SmsException("查询所有角色的信息");
        }
        return list;
    }
    //@SystemServiceLog(description = "根据地市编码查询该地市下地市管理员", value = false)
    public List<SmsUsers> findCityUsersbyCityId(String cityId) {
        List<SmsUsers> list = new ArrayList<>();
        try {
            list = smsUserMapper.findCityUsersbyCityId(cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据地市编码查询该地市下地市管理员");
            throw new SmsException("根据地市编码查询该地市下地市管理员");
        }
        return list;
    }
   // @SystemServiceLog(description = "根据地市编码查询该地市下地市管理员", value = false)
    public List<SmsUsers> findCheckUsersbyCityId(String cityId) {
        List<SmsUsers> list = new ArrayList<>();
        try {
            list = smsUserMapper.findCheckUsersbyCityId(cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据地市编码查询该地市下地市管理员");
            throw new SmsException("根据地市编码查询该地市下地市管理员");
        }
        return list;
    }


    @SystemServiceLog(description = "获取用户id", value = false)
    public String findMaxUserId() {
        String userId;
        try {
            userId = smsUserMapper.findMaxUserId();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取用户id");
            throw new SmsException("获取用户id");
        }
        return userId;
    }

    public static void main(String[] args) {
        MD5 md5 = new MD5();
        System.out.println(md5.getMD5ofStr("4MQy7**#"));
    }

    @SystemServiceLog(description = "添加用户", value = false)
    public int addUser(String msisdn, String userName, String password, String duty, String cityId,String countyId, String mgrId, String roleId) {
    	MD5 md5 = new MD5();
    	password = md5.getMD5ofStr(password);
    	SmsUsers user = new SmsUsers();
        user.setUserId(findMaxUserId());
        user.setUserName(userName);
        user.setPassword(password);
        user.setDuty(duty);
        user.setCityId(cityId);
        user.setCountyId(countyId);
        user.setState("0");
        user.setMsisdn(msisdn);
        if (selectMsisdn(msisdn)) {
            if (mgrId.length() > 0) {
                if (",".equals(String.valueOf(mgrId.charAt(mgrId.length() - 1)))) {
                    mgrId = mgrId.substring(0, mgrId.length() - 1);
                }
            }
            user.setMgrId(mgrId);
            if (roleId.length() > 0) {
                if (",".equals(String.valueOf(roleId.charAt(roleId.length() - 1)))) {
                    roleId = roleId.substring(0, roleId.length() - 1);
                }
            }
            this.addUserRole(findMaxUserId(), roleId);
        } else {
            return -1;
        }
        int result;
        try {
            result = smsUserMapper.addUser(user);
            commonService.createSmsOperLog("2","添加用户"+userName,"0","用户管理");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加用户信息：" + user.getUserId());
            commonService.createSmsOperLog("2","添加用户"+userName,"1","用户管理");
            throw new SmsException("添加用户信息：" + user.getUserId());
        }
        return result;
    }

    @SystemServiceLog(description = "添加用户和角色的对应关系", value = false)
    public int addUserRole(String userId, String roleId) {
        String[] arr = roleId.split(",");
        int j = 0;
        for (int i = 0; i < arr.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("roleId", arr[i]);
            int result;
            try {
                result = smsUserMapper.addUserRole(map);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("添加用户和角色的对应关系：" + userId);
                throw new SmsException("添加用户和角色的对应关系：" + userId);
            }

            j++;
        }
        return j;
    }

    @SystemServiceLog(description = "根据用户的编号查询用户的信息", value = false)
    public SmsUsers findUserByUserId(String userId) {
        SmsUsers smsUsers = smsUserMapper.findUserByUserId(userId);
        List<SmsRule> roleList = new ArrayList<>();
        try {
            roleList = smsUserMapper.findRuleNameByUserid(smsUsers.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据用户的编号查询用户的信息：" + userId);
            throw new SmsException("根据用户的编号查询用户的信息：" + userId);
        }
        StringBuffer sbf = new StringBuffer();
        int i = 1;
        if (roleList.size() > 0) {
            for (SmsRule smsRule : roleList) {
                sbf.append(smsRule.getRoleId());
                if (i < roleList.size()) {
                    sbf.append(",");
                    i++;
                }
            }
            smsUsers.setSmsRuleId(sbf.toString());
        }
        return smsUsers;
    }

    @SystemServiceLog(description = "编辑用户的信息", value = false)
    public int modifyUser(String userId, String msisdn, String userName,  String duty, String cityId,String countyId, String mgrId, String roleId) {
        SmsUsers user = new SmsUsers();
        user.setUserId(userId);
        user.setUserName(userName);
       // user.setPassword(password);
        user.setDuty(duty);
        user.setCityId(cityId);
        user.setCountyId(countyId);
        user.setState("0");
        user.setMsisdn(msisdn);
        if (mgrId.length() > 0) {
            if (",".equals(String.valueOf(mgrId.charAt(mgrId.length() - 1)))) {
                mgrId = mgrId.substring(0, mgrId.length() - 1);
            }
        }
        user.setMgrId(mgrId);
        if (",".equals(String.valueOf(roleId.charAt(roleId.length() - 1)))) {
            roleId = roleId.substring(0, roleId.length() - 1);
        }
        String[] arr = roleId.split(",");
        this.deleteRoleByuserId(userId);
        this.addUserRole(userId, roleId);
        int result;
        try {
            result = smsUserMapper.modifyUser(user);
            commonService.createSmsOperLog("3","修改用户"+userId,"0","用户管理");
        } catch (Exception e) {
            e.printStackTrace();
            commonService.createSmsOperLog("3","修改用户"+userId,"1","用户管理");
            log.error("编辑用户的信息：" + userId);
            throw new SmsException("编辑用户信息：" + userId);
        }

        return result;
    }


    @SystemServiceLog(description = "删除用户的角色", value = false)
    public int deleteRoleByuserId(String userId) {
        int result;
        try {
            result = smsUserMapper.deleteRoleByuserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除用户的角色：" + userId);
            throw new SmsException("删除用户的角色：" + userId);
        }
        return result;
    }


    @SystemServiceLog(description = "删除用户", value = false)
    public int deleteUser(String userId) {
        int result;
        try {
            result = smsUserMapper.deteteUser(userId);
            this.deleteRoleByuserId(userId);
            commonService.createSmsOperLog("5","删除用户"+userId,"0","用户管理");
        } catch (Exception e) {
            e.printStackTrace();
            commonService.createSmsOperLog("5","删除用户"+userId,"1","用户管理");
            log.error("删除用户：" + userId);
            throw new SmsException("删除用户：" + userId);
        }
        return result;
    }


    @SystemServiceLog(description = "检验手机号是否重复", value = false)
    public Boolean selectMsisdn(String msisdn) {
        String count;
        try {
            count = smsUserMapper.selectMsisdn(msisdn);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("检验手机号是否重复：" + msisdn);
            throw new SmsException("检验手机号是否重复：" + msisdn);
        }
        if ("0".equals(count)) {
            return true;
        } else {
            return false;
        }
    }


    @SystemServiceLog(description = "查询项目管理员的手机号", value = false)
    public List<SmsUsers> getMsisdn(String mgrId) {
        List list;
        try {
            list = smsUserMapper.getMsisdn(mgrId);
            log.info("查询项目管理员的手机号：" + mgrId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询项目管理员的手机号：" + mgrId);
            throw new SmsException("查询项目管理员的手机号：" + mgrId);
        }
        return list;
    }

    @SystemServiceLog(description = "根据城市id查询扩展码信息", value = false)
    public List<String> findExtIdByCityId(String cityId) {
        List list = new ArrayList();
        try {
            list = smsUserMapper.findExtIdByCityId(cityId);
            log.info("根据城市id查询扩展码信息：" + cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据城市id查询扩展码信息：" + cityId);
            throw new SmsException("根据城市id查询扩展码信息：" + cityId);
        }
        return list;
    }
    @SystemServiceLog(description = "根据地市的id查询区县信息", value = false)
    public List<SmsCounty> findCountyByCityId(String cityId) {
        List<SmsCounty> list = new ArrayList<SmsCounty>();
        try {
            list = smsUserMapper.findCountyByCityId(cityId);
            log.info("根据地市的id查询区县信息：" + cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据地市的id查询区县信息：" + cityId);
            throw new SmsException("根据地市的id查询区县信息：" + cityId);
        }
        return list;
    }
    
    @SystemServiceLog(description = "根据地市的id查询经分区县信息", value = false)
    public List<SmsCounty> findJFCountyByCityId(String cityId) {
        List<SmsCounty> list = new ArrayList<SmsCounty>();
        try {
            list = smsUserMapper.findJFCountyByCityId(cityId);
            log.info("根据地市的id查询区县信息：" + cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据地市的id查询区县信息：" + cityId);
            throw new SmsException("根据地市的id查询区县信息：" + cityId);
        }
        return list;
    }
    
    @SystemServiceLog(description = "根据区县的id查询项目信息", value = false)
    public List<SmsMgrTemplateInfo> findMgrByCountyId(String countyId,String duty,String msisdn) {
        List<SmsMgrTemplateInfo> list = new ArrayList<SmsMgrTemplateInfo>();
        try {
            list = smsUserMapper.findMgrByCountyId(countyId,duty,msisdn);
            log.info("根据区县的id查询项目信息：" + countyId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据区县的id查询项目信息：" + countyId);
            throw new SmsException("根据区县的id查询项目信息：" + countyId);
        }
        return list;
    }
    
    @SystemServiceLog(description = "根据地市的id查询项目信息", value = false)
    public List<SmsMgrTemplateInfo> findMgrByCityId(String cityId,String duty,String msisdn) {
        List<SmsMgrTemplateInfo> list = new ArrayList<SmsMgrTemplateInfo>();
        try {
            list = smsUserMapper.findMgrByCityId(cityId,duty,msisdn);
            log.info("根据地市的id查询项目信息：" + cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据地市的id查询项目信息：" + cityId);
            throw new SmsException("根据地市的id查询项目信息：" + cityId);
        }
        return list;
    }
    
    @SystemServiceLog(description = "查询区县名称", value = false)
    public String getCountyName(String countyId) {
        String countyName="";
        try {
             List<String> list = Arrays.asList(countyId.split(","));
             List<String> countyNameList = smsUserMapper.getCountyName(list);
             countyName=org.apache.commons.lang3.StringUtils.join(countyNameList, ",");
             log.info("查询区县名称信息：" + countyId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询区县名称信息：" + countyId);
            throw new SmsException("查询区县名称信息：" + countyId);
        }
        return countyName;
    }
    
    @SystemServiceLog(description = "获取项目名称是否存在", value = false)
    public int getMgrName(String mgrName) {
        int flag=0;
        try {
        	 flag = smsUserMapper.getMgrName(mgrName);
             log.info("获取项目名称是否存在：" + flag);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取项目名称是否存在：" + flag);
            throw new SmsException("获取项目名称是否存在：" + flag);
        }
        return flag;
    }
    
    @SystemServiceLog(description = "项目名称联想", value = false)
    public List<SmsMgrTemplateInfo> selectMgrNameLike(String key,String cityId,String countyId){
        List<SmsMgrTemplateInfo> list= commonService.selectMgrNameLike(key,cityId,countyId);
        return list;
    }

	public List<SmsUsers> findXuYiSubCheck() {
		List<SmsUsers> list = new ArrayList<>();
        try {
            list = smsUserMapper.findXuYiSubCheck();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询盱眙供电局领导列表");
            throw new SmsException("查询盱眙供电局领导列表出现异常");
        }
        return list;
	}
    
}
